import React, { useState, useEffect } from 'react';
import axios from 'axios';

import './RemoveMemberModal.css';
import '../../../assets/icons/iconfont.css';
import Icon from '../../Icon';

interface UserData {
  _id?: string;
  username: string;
  image: string;
  isLoggedIn: boolean;
}

interface RemoveMemberModalProps {
  isOpen: boolean;
  onClose: () => void;
  onRemoveMember: (userId: string) => void;
  currentGroupId: string;
  currentMembers: UserData[];
  currentUser: UserData;
  groupCreator: string;
}

const RemoveMemberModal: React.FC<RemoveMemberModalProps> = ({
  isOpen,
  onClose,
  onRemoveMember,
  currentMembers,
  currentUser,
  groupCreator,
}) => {
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedUser, setSelectedUser] = useState<string | null>(null);

  // 过滤可移除的成员（只排除群主，群主不能移除自己）
  const removableMembers = currentMembers.filter(member => {
    const isNotCreator =
      member._id !== groupCreator && member.username !== groupCreator;
    return isNotCreator;
  });

  // 过滤用户列表
  const filteredMembers = removableMembers.filter(member =>
    member.username.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 处理用户选择
  const handleUserSelect = (userId: string) => {
    setSelectedUser(userId);
  };

  // 移除选中的用户
  const handleRemoveSelectedUser = async () => {
    if (!selectedUser) {
      alert('请选择要移除的用户');
      return;
    }

    try {
      setLoading(true);
      await onRemoveMember(selectedUser);
      setSelectedUser(null);
      onClose();
    } catch (error) {
      console.error('移除群成员失败:', error);
      alert('移除群成员失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  // 检查当前用户是否为群主
  const isCurrentUserCreator =
    currentUser._id === groupCreator || currentUser.username === groupCreator;

  if (!isCurrentUserCreator) {
    return (
      <div className="remove-member-modal-overlay">
        <div className="remove-member-modal">
          <div className="remove-member-modal-header">
            <button className="cancel-btn" onClick={onClose}>
              取消
            </button>
            <h3>权限不足</h3>
            <div></div>
          </div>
          <div className="remove-member-modal-content">
            <div className="no-members">只有群主可以移除群成员</div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="remove-member-modal-overlay">
      <div className="remove-member-modal">
        <div className="remove-member-modal-header">
          <button className="cancel-btn" onClick={onClose}>
            取消
          </button>
          <h3>移除群成员</h3>
          <button
            className="confirm-btn"
            onClick={handleRemoveSelectedUser}
            disabled={!selectedUser || loading}
          >
            {loading ? '移除中...' : '确定'}
          </button>
        </div>

        <div className="remove-member-modal-content">
          {/* 搜索框 */}
          <div className="search-container">
            <input
              type="text"
              placeholder="搜索成员"
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              className="search-input"
            />
            <Icon iconClass="icon-search" className="search-icon" />
          </div>

          {/* 成员列表 */}
          <div className="members-list">
            {filteredMembers.length === 0 ? (
              <div className="no-members">
                {searchTerm ? '没有找到匹配的成员' : '没有可移除的成员'}
              </div>
            ) : (
              filteredMembers.map(member => (
                <div
                  key={member._id || member.username}
                  className={`member-item ${selectedUser === (member._id || member.username) ? 'selected' : ''}`}
                  onClick={() =>
                    handleUserSelect(member._id || member.username)
                  }
                >
                  <div className="member-avatar">
                    {member.image ? (
                      <img src={member.image} alt={member.username} />
                    ) : (
                      <div className="default-avatar">
                        {member.username.charAt(0).toUpperCase()}
                      </div>
                    )}
                  </div>
                  <div className="member-info">
                    <div className="member-name">{member.username}</div>
                  </div>
                  <div className="member-radio">
                    {selectedUser === (member._id || member.username) && (
                      <Icon iconClass="icon-check" className="check-icon" />
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default RemoveMemberModal;
